const express = require('express')
const app = express()

const bodyParser = require('body-parser')
// application/x-www-form-urlencoded
app.use( bodyParser.urlencoded({ extended: false }) )
// application/json
app.use( bodyParser.json() )

const session = require('express-session')
app.use(session({
  secret: 'zx22',
  resave: false,
  saveUninitialized: true
}))

//设置静态文件
app.use(express.static('public'))

//设置相应中文乱码
app.use((req, res, next) => {
  res.set({
    'Content-Type': 'application/json;charset=utf-8'
  })
  next()
})

const jwt = require('./token/token.js')
//验证token 并把解析后的user对象挂载到req对象上 之后根据req.user对象判断用户是否登录
app.use((req, res, next) => {
  try {
    let token = req.headers['authorization']
    let user = jwt.getToken(token)
    req.user = user
    console.log(req.user)
    next()
  } catch (error) {
    if (error.message == 'jwt expired') {
      res.status(200).json({
        reLogin: true
      })
    } else {
      next()
    }
  }
  
})

app.use(require('./router/consumerRouter.js'))
app.use(require('./router/deliveryAddressRouter.js'))
app.use(require('./router/goodsRouter.js'))
app.use(require('./router/indentRouter.js'))

app.listen(3000, () => {
  console.log('server is running at http://127.0.0.1:3000')
})